<?php
/**
 * 统计
 * User: cxm
 * Date: 2020/9/5
 * Time: 9:27
 */
namespace App\Http\Controllers\Admin\Count;
use App\Models\Activity;
use App\Models\AwardGoods;
use App\Models\AwardHistory;
use App\Models\User;
use App\Models\UserStepRecord;
use Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CountController extends  StatisticsController {
    /**
     * 用户统计
     * URL POST:/admin/count/userStatistic
     * @param Request $request
     * @param int time_type days日 month月 quarter季度 year年
     * @param string start_time 开始时间
     * @param string end_time 结束时间
     * @return mixed
     */
    public function userStatistic(Request $request){
        $params = $request->only(['time_type','start_time','end_time']);
        $start_time   = isset($params['start_time']) ? $params['start_time'] : '';
        $end_time  = isset($params['end_time']) ? $params['end_time'] : '';
        $time_type = isset($params['time_type']) ? $params['time_type'] : 'days'; // 时间类型默认为日
        // 结束时间是否大于开始时间
        if ($start_time > $end_time) {
            return $this->error( '时间范围错误');
        }
        // 默认数据
        $data = [
            'data' => [], // 用户统计
            'times' => [] // 时间
        ];
        // 调用时间数组方法
        $times = $this->getDateByInterval($start_time, $end_time, $time_type);

        $data['times'] = array_column($times,'name');

        if ($time_type != 'quarter') {
            $status_1 = $this->selectUser($start_time, $end_time, $time_type);
            $times = array_column($times,'name');
            // 数据重组
            foreach ($times as $time) {
                $data['data'][] = isset($status_1[$time]) ? $status_1[$time] : 0;
            }
        }else{
            foreach ($times as $item) {
                $data['data'][] = User::statisticsByTime($item['startDate'],$item['endDate']);
            }
        }

        $data['args'] = http_build_query($params);

//         echo "<pre>";print_r($data);die;
        return $this->success('操作成功', $data);
    }

    /**
     * 活动列表
     * URL POST:/admin/count/regularActivity
     * @param Request $request
     * @return mixed
     */
    public function regularActivity(Request $request){
        $params['field'] = ['id','name'];
        $data = Activity::getAll($params);
        return $this->success('查询成功',$data);
    }

    /**
     * 转盘中奖、领取情况
     * URL POST:/admin/count/randomStatistic
     * @param Request $request
     * @param int activity_id 活动ID
     * @param int time_type days日 month月 quarter季度 year年
     * @param string start_time 开始时间
     * @param string end_time 结束时间
     * @return mixed
     */
    public function randomStatistic(Request $request){
        $params = $request->only(['activity_id','time_type','start_time','end_time']);
        $start_time   = isset($params['start_time']) ? $params['start_time'] : '';
        $end_time  = isset($params['end_time']) ? $params['end_time'] : '';
        $time_type = isset($params['time_type']) ? $params['time_type'] : 'days'; // 时间类型默认为日
        // 结束时间是否大于开始时间
        if ($start_time > $end_time) {
            return $this->error( '时间范围错误');
        }
        // 默认数据
        $data = [];
        // 调用时间数组方法
        $times = $this->getDateByInterval($start_time, $end_time, $time_type);
        $data['times'] = array_column($times,'name');
        // 查询奖项
        $award_where = [];
        $award_where['where'][] = ['activity_id',$params['activity_id']];
        $award_where['field'] = ['id','name'];
        $award_where['orderBy'] = ['sort asc'];
        $awards = AwardGoods::getAll($award_where);
        // 查询的内容
        $names = [];
        // 对应数据
        $record = [];
        foreach ($awards as $key=>$item) {
            $name = $item['name'];
            $names[] = $name.'(中奖数量)';
            $names[] = $name.'(领取数量)';
            $arr = $this->userAwardData($name,$item['id'],$time_type,$start_time, $end_time,$times);
            if (empty($record)) {
                $record = $arr;
            }else{
                $record = array_merge($record,$arr);
            }
        }
        $data['record'] = $record;
        $data['names'] = $names;
        return $this->success('查询成功',$data);
    }

    /**
     * 查询指定活动的领取情况
     * @param $name 名称
     * @param $award_id 奖项ID
     * @param $time_type 时间类型
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $times 时间段
     * @return mixed
     */
    public function userAwardData($name,$award_id,$time_type,$start_time,$end_time,$times){
        if ($time_type != 'quarter') {
            // 中奖数量
            $prize = $this->selectUserAwards($award_id,$start_time,$end_time,$time_type,1);
            // 领取数量
            $receive = $this->selectUserAwards($award_id,$start_time,$end_time,$time_type,2);
            $times = array_column($times,'name');
            $prizeData = $receiveData = [];
            foreach ($times as $time) {
                $prizeData[] =  isset($prize[$time]) ? $prize[$time] : 0;
                $receiveData[] =  isset($receive[$time]) ? $receive[$time] : 0;
            }
        }else{
            $prizeData = $receiveData = [];
            foreach ($times as $item) {
                $prizeData[] = AwardHistory::statisticsAwardsByTime($award_id,$item['startDate'],$item['endDate'],false);
                $receiveData[] = AwardHistory::statisticsAwardsByTime($award_id,$item['startDate'],$item['endDate'],true);
            }
        }

        $data = [
            [
                'name'  => $name.'(中奖数量)',
                'data'  => $prizeData
            ],[
                'name'  => $name.'(领取数量)',
                'data'  => $receiveData
            ]
        ];
        return $data;
    }

    /**
     * 用户参与情况统计
     * URL POST:/admin/count/userJoinStatistic
     * @param Request $request
     * @param int activity_id 活动ID
     * @param int time_type days日 month月 quarter季度 year年
     * @param string start_time 开始时间
     * @param string end_time 结束时间
     * @return mixed
     */
    public function userJoinStatistic(Request $request){
        $params = $request->only(['activity_id','time_type','start_time','end_time']);
        $activity_id = isset($params['activity_id']) ? $params['activity_id'] :1; // 默认1
        $start_time   = isset($params['start_time']) ? $params['start_time'] : '';
        $end_time  = isset($params['end_time']) ? $params['end_time'] : '';
        if (!empty($start_time)) {
            $params['where'][] = ['date','>=',$start_time];
        }
        if (!empty($end_time)) {
            $params['where'][] = ['date','<=',$end_time];
        }
        // 用户信息
        $params['with'][] = 'user:id,name,mobile';
        $data = UserStepRecord::listByWhere($params);
        return $this->success('操作成功', $data);
    }

    /**
     * 用户参与情况导出
     * URL POST:/admin/count/userJonExport
     * @param Request $request
     * @param int time_type days日 month月 quarter季度 year年
     * @param string start_time 开始时间
     * @param string end_time 结束时间
     * @return mixed
     */
    public function userJoinExport(Request $request){
        $params = $request->only(['time_type','start_time','end_time']);
        // 设置内存
        ini_set('memory_limit','100M');
        //设置超时限制为0分钟(无限制, 默认30s)
        set_time_limit(0);
        $start_time   = isset($params['start_time']) ? $params['start_time'] : '';
        $end_time  = isset($params['end_time']) ? $params['end_time'] : '';
        if (!empty($start_time)) {
            $params['where'][] = ['date','>=',$start_time];
        }
        if (!empty($end_time)) {
            $params['where'][] = ['date','<=',$end_time];
        }
        // 用户信息
        $params['with'][] = 'user:id,name,mobile,card_no';
        $data = UserStepRecord::getAll($params);
        //session()->put('excel_data');
        return Excel::download(new \App\Excel\UserJoinExport($data), time().'_用户参与信息导出.xlsx');
    }

    /**
     * 用户参与情况图表统计
     * URL POST:/admin/count/userJoinChart
     * @param Request $request
     * @param int time_type days日 month月 quarter季度 year年
     * @param string start_time 开始时间
     * @param string end_time 结束时间
     * @return mixed
     */
    public function userJoinChart(Request $request){
        $params = $request->only(['activity_id','time_type','start_time','end_time']);
        $activity_id = isset($params['activity_id']) ? $params['activity_id'] :1; // 默认1
        $start_time   = isset($params['start_time']) ? $params['start_time'] : '';
        $end_time  = isset($params['end_time']) ? $params['end_time'] : '';
        $time_type = isset($params['time_type']) ? $params['time_type'] : 'days'; // 时间类型默认为日
        // 结束时间是否大于开始时间
        if ($start_time > $end_time) {
            return $this->error( '时间范围错误');
        }
        // 默认数据
        $data = [
            'data1' => [], // 总步数
            'data2' => [], // 参与人数
            'times' => [] // 时间
        ];
        // 调用时间数组方法
        $times = $this->getDateByInterval($start_time, $end_time, $time_type);
        $data['times'] = array_column($times,'name');
        if ($time_type != 'quarter') {
            // 总步数
            $status_1 = $this->selectUserJoin($start_time, $end_time, $time_type,'total');
            // 参与人数
            $status_2 = $this->selectUserJoin($start_time, $end_time, $time_type,'num');
            if ($time_type == 'year') {
                $times = array_column($times,'name_str');
            }else{
                $times = array_column($times,'name');
            }
            // 数据重组
            foreach ($times as $time) {
                $data['data1'][] = isset($status_1[$time]) ? $status_1[$time] : 0;
                $data['data2'][] = isset($status_2[$time]) ? $status_2[$time] : 0;
            }
        }else{
            foreach ($times as $item) {
                $data['data1'][] = UserStepRecord::statisticsStepsByTime($item['startDate'],$item['endDate']); // 总步数
                $data['data2'][] = UserStepRecord::statisticsNumByTime($item['startDate'],$item['endDate']);
            }
        }
        $data['args'] = http_build_query($params);

//         echo "<pre>";print_r($data);die;
        return $this->success('操作成功', $data);
    }
}